//
//  NavigationBarView.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/5.
//
// 自定义 导航栏

import SwiftUI

struct NavigationBar: View {
    let title: String
    var isBackBtnVisible: Bool = true
    var onBack: (() -> Void)?

    var leading: AnyView?
    var trailing: AnyView?
    var backgroundColor: Color = .white
    var titleColor: Color = .black
    var showDivider: Bool = false
    var height: CGFloat = 44

    @Environment(\.presentationMode) private var presentationMode

    var body: some View {
        ZStack {
            VStack(spacing: 0) {
                HStack {
                    if let leading = leading {
                        leading
                            .frame(width: 44, height: height, alignment: .center)
                    } else {
                        Button(action: {
                            onBack?() ?? presentationMode.wrappedValue.dismiss()
                        }) {
                            Image(systemName: "chevron.left")
                                .font(.system(size: 18, weight: .medium))
                                .foregroundColor(titleColor)
                        }
                        .frame(width: 44, height: height)
                        .opacity(isBackBtnVisible ? 1 : 0)
                    }

                    Spacer()

                    Text(title)
                        .font(.system(size: 18, weight: .semibold))
                        .foregroundColor(titleColor)
                        .lineLimit(1)

                    Spacer()

                    if let trailing = trailing {
                        trailing
                            .frame(width: 44, height: height, alignment: .center)
                    } else {
                        Spacer().frame(width: 44, height: height)
                    }
                }
                .padding(.horizontal, 8)
                .frame(height: height)

                if showDivider {
                    Divider()
                }
            }
        }.background(backgroundColor)
    }
}

extension UIApplication {
    static var topSafeAreaInset: CGFloat {
        let window = UIApplication.shared
            .connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first { $0.isKeyWindow }

        return window?.safeAreaInsets.top ?? 0
    }
}
